#include <iostream>
#include <sstream>
#include "IdMap.h"
#include "vest.h"

using namespace std;


unordered_map<string, string> * IdMap::GetHash() {
	return  &_hash;
}

bool IdMap::Add(const string key, const string value) {
	unique_lock<mutex> lock(_mu);
	auto ret = _hash.emplace(make_pair(key, value));
	return ret.second;
}

void IdMap::Delete(const string key) {
	unique_lock<mutex> lock(_mu);
	_hash.erase(key);
}

bool IdMap::Update(const string key, const string value) {
	unique_lock<mutex> lock(_mu);
	auto it = _hash.find(key);
	if (it != _hash.end()) {
		it->second = value;
		return true;
	}
	else {
		return false;
	}
}

string IdMap::ToString() {
	unique_lock<mutex> lock(_mu);
	ostringstream oss;
	oss << "dump " << _name.c_str() << ": ";
	for (auto it : _hash) {
		oss << "{" << it.first << ", " << it.second << "}, ";
	}
	oss << endl;
	return oss.str();
}

void IdMap::Clear() {
	unique_lock<mutex> lock(_mu);
	_hash.clear();
}

int IdMap::GetCount() {
	unique_lock<mutex> lock(_mu);
	return (int)_hash.size();
}

string IdMap::Find(const string key) {
	unique_lock<mutex> lock(_mu);
	auto ret = _hash.find(key);
	if (ret == _hash.end()) {
		return "";
	}
	return ret->second;
}

bool IdMap::CheckMapName(const string expectedMapName) 
{
	if (this->_name != expectedMapName)
	{
		logs(error_, "CheckMapName failed, the name of map is " + _name);
		return false;
	}
	return true;
}
string IdMap::GetMapName()
{
	return _name;
}
